<?php

namespace API\App\Model;

use Hx\App;

class Category {

    /**
     * 数据库对象
     * @var \Hx\Db
     */
    private $db;

    /**
     * 构造函数
     */
    public function __construct() {
        $this->db = App::Db();
    }

    public function getAll() {
        $sql = App::Sql('HxSite_Category', 'id,name,keyString,nodeCount,createDate,desc')
            ->where('status = "public"')
            ->order('nodeCount DESC')
            ->select();
        return $this->db->queryAll($sql);
    }

    public function getOne($id) {
        $sql = App::Sql('HxSite_Category')
            ->where('status = "public"')
            ->where('id = :id')
            ->select();
        return $this->db->query($sql, array('id' => $id));
    }

    /**
     * 更新分类下文章计数
     */
    public function updateCount() {
        $sql = App::Sql('HxSite_Category', 'nodeCount')
            ->update();
        $sql2 = App::Sql('HxSite_Node AS N')
            ->where('N.status = "public" AND N.nodeType="blog"')
            ->where('HxSite_Category.id = N.categoryId')
            ->count();
        $sql = str_replace(':nodeCount', '(' . $sql2 . ')', $sql);
        $this->db->exec($sql);
    }

    public function addCategory($data) {
        if ($this->isKeyExist($data['keyString'])) {
            return false;
        }
        $data['createDate'] = time();
        $data['status'] = 'public';
        $data['parentId'] = 0;
        $sql = App::Sql('HxSite_Category', 'name,keyString,desc,createDate,status,parentId')
            ->insert();
        $this->db->exec($sql, $data);
        return $this->getOne($this->db->lastId());
    }

    public function updateCategory($data) {
        if ($this->isKeyExist($data['keyString'], $data['id'])) {
            return false;
        }
        $sql = App::Sql('HxSite_Category', 'name,keyString,desc')
            ->where('id = :id')
            ->update();
        $this->db->exec($sql, $data);
        return $this->getOne($data['id']);
    }

    private function isKeyExist($key, $id = 0) {
        $sql = App::Sql('HxSite_Category', 'id')
            ->where('keyString = :key')
            ->select();
        $data = $this->db->query($sql, array('key' => $key));
        if (!$data) {
            return false;
        }
        if ($id) {
            if ($data->id == $id) {
                return false;
            }
        }
        return true;
    }

    public function deleteCategory($id, $move) {
        if ($id == $move) {
            return false;
        }
        $sql = App::Sql('HxSite_Node', 'categoryId')
            ->where('categoryId = :id')
            ->update();
        $this->db->exec($sql, array('categoryId' => $move, 'id' => $id));
        $sql = App::Sql('HxSite_Category')
            ->where('id = :id')
            ->delete();
        return $this->db->exec($sql, array('id' => $id));
    }
}